package com.ws.base.db.common.page;

public class Page {
    public static String pageType = "";

    protected int pageSize;

    protected int totalPage;

    protected int currentPage;

    protected boolean hasNextPage;

    protected boolean hasPreviousPage;

    protected int startNum;

    protected int totalRows;

    public Page() {
        this.pageSize = 10;
        this.currentPage = 1;
    }

    public Page(int currentPage, int pageSize) {
        this.pageSize = pageSize;
        this.currentPage = currentPage;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public boolean isHasNextPage() {
        return hasNextPage;
    }

    public boolean isHasPreviousPage() {
        return hasPreviousPage;
    }

    public int getTotalRows() {
        return totalRows;
    }

    public int getPageSize() {
        return pageSize;
    }

    public final String setPageStr(String sql) {
        if ("mysql".equalsIgnoreCase(pageType)) {
            repaginate();
            int start = startNum - 1;
            sql = sql + " LIMIT " + start + "," + getPageSize();
            return sql;
        } else if ("oracle".equalsIgnoreCase(pageType)) {
            repaginate();
            int endNum = startNum + pageSize - 1;
            sql = "SELECT * FROM (SELECT ROW_.*, ROWNUM ROWNUM_ FROM (" + sql
                    + ") ROW_ WHERE ROWNUM <= " + endNum + ")WHERE ROWNUM_ >= "
                    + startNum;
            return sql;
        }
        return sql;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public void setTotalRows(int totalRows) {
        this.totalRows = totalRows;
    }

    protected void repaginate() {
        if (totalRows % pageSize == 0)
            totalPage = totalRows / pageSize;
        else
            totalPage = totalRows / pageSize + 1;
        if (currentPage >= totalPage) {
            hasNextPage = false;
            currentPage = totalPage;
        } else {
            hasNextPage = true;
        }
        if (currentPage <= 1) {
            hasPreviousPage = false;
            currentPage = 1;
        } else {
            hasPreviousPage = true;
        }
        startNum = (currentPage - 1) * pageSize + 1;
    }
}
